A Step-by-Step Process to Override Controller in Magento 2
-
Nidhi Arora
- 9 years

Today, we’re going to explain how to override controller in Magento 2 and hope you are already familiar with controller & its functionality. Controller basically stands behind the process of handling incoming requests and it plays a significant role in Magento 2 routing implementation. Controller overriding is mainly required while working on custom modules in Magento 2 and you need to work on overriding core module files.
By following the simple steps as mentioned below, you can easily override the controller in Magento 2 and we hope that you can grab that “Ah-ha!” moment. Or at the very least you’ll say, “That’s very easy.”
Step1)
Create di.xml file in app/code/<VendorName>/<ModuleName>/etc <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Checkout\Controller\Cart\Add" type="<VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add" /> </config> Code Explanation <VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add is used to override Magento\Checkout\Controller\Cart\Add
Step2)
Define an overriding controller class
Create Add.php in app/code/<VendorName>/<ModuleName>/Controller/Rewrite/Cart/ <?php namespace <VendorName>\<ModuleName>\Controller\Rewrite\Cart; class Add extends \Magento\Checkout\Controller\Cart\Add { public function execute() { // perform action }
Conclusion
In Magento 2, the controller is a crucial part of the MVC flow. Overriding a controller in Magento 2 gives developers the flexibility to change the main functionality according to Magento 2 module development needs. Hope this guide on overriding controllers makes Magento 2 development a bit easier for you! If you need further assistance for your Magento 2 project, get in touch with the experts at Envision eCommerce.
Download Blog